/**
 * Created by swing on 2017/5/21.
 */

var server = require('api');
var _alert = require('alert');
var _clear = require('clearForm');
var $url = server.queryTask;
var columns =  [
    {
        field: 'state',
        title: '投入硬币',
        align: 'center',
        radio: true
    },
    {
        field: 'taskName',
        title: '任务名称',
        align: 'center'
    },
    {
        field: 'taskTypeName',
        title: '任务类型名称',
        align: 'center'
    },
    {
        field: 'depTypeName',
        title: '科室名称',
        align: 'center'
    },
    {
        field: 'branchName',
        title: '支队名称',
        align: 'center'
    },
    {
        field: 'releaseTime',
        title: '发布时间',
        align: 'center'
    },
    {
        field: 'startTime',
        title: '开始时间',
        align: 'center'
    },
    {
        field: 'endTime',
        title: '结束时间',
        align: 'center'
    },
    {
        field: 'taskWeight',
        title: '权重',
        align: 'center',
        width: 1
    },
    {
        field: 'taskDES',
        title: '描述',
        align: 'center'
    },
    {
        field: 'taskCompletion',
        title: '完成度',
        align: 'center'
    },
    {
        field: 'taskFinishDES',
        title: '完成度描述',
        align: 'center'
    }
]
function queryParams() {   //设置查询参数
    var param = {
        userId: '111',
        userToken: '1111'
    };
    return param;
}

//TODO: use js to init table, have problem
// var initTbale = function(){
//     $('#uploadTable').bootstrapTable('destroy').bootstrapTable({
//         method: "get",  //使用get请求到服务器获取数据
//         cache: false,
//         url: $url, //获取数据的Servlet地址
//         striped: true,  //表格显示条纹
//         pagination: true, //启动分页
//         pageSize: 1,  //每页显示的记录数
//         pageNumber:1, //当前第几页
//         pageList: [5, 10, 15, 20, 25],  //记录数可选列表
//         search: false,  //是否启用查询
//         showColumns: true,  //显示下拉框勾选要显示的列
//         showRefresh: true,  //显示刷新按钮
//         sidePagination: "server", //表示服务端请求
//         //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
//         //设置为limit可以获取limit, offset, search, sort, order
//         queryParamsType : "limit",
//         queryParams: queryParams,
//         onLoadSuccess: function(){  //加载成功时执行
//             _alert("加载成功");
//         },
//         onLoadError: function(){  //加载失败时执行
//             _alert('加载失败');
//         },
//         columns: columns
//     })
// }

// function writeOut(val, i, arr) {
//     var order = i + 1;
//     var tsName = val.tsName;
//     var tsDES = val.tsDES;
//     var tsCompletion = val.tsCompletion;
//     var tsState = val.tsState;
//     var link = val.tsAtt;
//
//     var html = '<div class="detailModal"><p>名称：'+ tsName +'</p><p>描述：'+tsDES+'</p>' +
//         '<p>完成度：'+tsCompletion+'</p><p>状态：'+ tsState +'</p><p><a href=link>下载附件</a></p><hr></div>';
//
//     $('#detailModalBody').append(html);
//
//
// }


function showState2(state) {

    if (state == '0'){
        return '未上报';
    } else if(state == '1'){
        return '已上报未审批';
    }else if(state == '2'){
        return '已审批未通过';
    }else if(state == '3'){
        return '已审批已通过';
    }
}


//显示任务详细信息modal
window.showUpTaskDetail = {
    'click .UptaskInfo' : function (e, value, row, index) {

        $('#uptaskDetailModal').modal('show');

        if (row){
            $('#uptaskDetailName').text(row.taskName);
            $('#uptaskDetailContent').text(row.taskDES);

            if (row.taskAtt){
                $('#uptaskDetailFile').attr('href',row.taskAtt);
            }else{
                $('#uptaskDetailFile').attr('disabled','disabled');
            }

        }
    }
}


//显示任务阶段detail
window.upDetailEv = {
    'click .upDetail': function (e, value, row, index) {
        $('#upDetailTaskProgress').empty();
        var taskId = row.taskId;

        $.ajax({
            url: server.jd,
            type: 'get',
            dataType: 'json',
            data: {
                userId: avalon.vmodels.root.user.id,
                userToken:avalon.vmodels.root.user.token,
                taskId:taskId
            }
        })
            .done(function(res) {

                if(res.status == '9200'){
                    var data = res.values;

                    for (var i=0;i<data.length;i++){
                        var val = data[i];
                        // var order = i + 1;
                        var tsName = val.tsName;
                        var tsDES = val.tsDES;
                        var tsCompletion = val.tsCompletion;
                        var tsState = val.tsState;
                        var link = val.tsAtt;
                        var stateText = showState2(tsState);
                        var content = val.tsReportDES;


                        if (link) {

                            var html = '<div class="detailModal"><p>名称：'+ tsName +'</p><p>描述：'+tsDES+'</p>' +
                                '<p>占比：'+tsCompletion+'</p><p>内容：'+content+'</p><p>状态：'+ stateText +'</p><p><a target="_blank" href=' + link + '>下载附件</a></p><hr></div>';
                        }else {

                            var html = '<div class="detailModal"><p>名称：'+ tsName +'</p><p>描述：'+tsDES+'</p>' +
                                '<p>占比：'+tsCompletion+'</p><p>内容：'+content+'</p><p>状态：'+ stateText +'</p><hr></div>';
                        }

                        $('#upDetailTaskProgress').append(html);
                    }
                    // data.forEach(writeOut);
                    $('#upTaskJdDetail').modal('show');
                }else{
                    _alert(res.description);
                }
            })
            .fail(function(res) {
                _alert('网络错误，请刷新尝试！');
                avalon.log(JSON.parse(res) + _.now())
            })

        $('#upTaskJdDetail').modal('show');

        $('#upTaskJdDetail').on('hide.bs.modal',function () {
            $('#detailModalBody').html('');
        })
    }
};

//查询任务列表
function queryTaskList() {

    uploadTask.upload.taskId = '';
    // $('#uploadTable').bootstrapTable('removeAll');
    // $('#uploadTable').bootstrapTable('destroy').bootstrapTable({
    //     columns: columns
    // })

    $.ajax({
        url: server.queryTask,
        type: 'get',
        dataType: 'json',
        data: {
            userId:avalon.vmodels.root.user.id,
            userToken:avalon.vmodels.root.user.token
        }
    })
        .done(function(res) {
            var data = res.values;
            if(res.status == '9200'){
                $('#uploadTable').bootstrapTable({});

                setTimeout(function () {
                    $('#uploadTable').bootstrapTable('load', data);

                    $('#uploadTable').on('check.bs.table', function (e,row) {
                        uploadTask.upload.taskId = row.taskId;
                    })
                },100)

            }else{
                $('#uploadTable').bootstrapTable('removeAll');
                $('#uploadTable').bootstrapTable({});
            }
        })
        .fail(function(res) {
            _alert('网络错误，请刷新尝试！');
        })
}

var uploadTask = avalon.define({
    $id : 'uploadTask',
    upload:{
        startTime: '',
        endTime: '',
        taskReportDES: '',
        taskId: '',
        jdList: '',
        fileAdrr: '',
        tsId: ''
    },


    init : function () {
        avalon.log('上报任务init' +_.now());

        setTimeout(function () {

            $(function () {
                queryTaskList();
            })

        },100)
    },


    upploadTaskModal: function () {

        _clear($('#upploadTaskModal'));
        if (uploadTask.upload.taskId){
            gainTaskId()
        } else{
            _alert('请先选择任务')
        }
    },


    // 上报任务
    uploadTask:function () {

        var data = {
            userId: avalon.vmodels.root.user.id,
            userToken:avalon.vmodels.root.user.token,
            // taskCompletion:uploadTask.upload.taskCompletion,
            taskReportDES:uploadTask.upload.taskReportDES,
            taskId:uploadTask.upload.taskId,
            tsAtt:uploadTask.upload.fileAdrr,
            tsId: $('#selectTs').val()
        }

        $.ajax({
            url: server.jdup,
            type: 'post',
            dataType: 'json',
            headers: {
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(data)
        })
            .done(function (res) {

                if  (res.status == '9200'){
                    _alert('任务上报成功');
                    $('#upploadTaskModal').modal('hide');
                    _clear($('#upploadTaskModal'));
                    queryTaskList();
                }else {
                    _alert(res.description);
                    $('#upploadTaskModal').modal('hide');
                }

            })
            .fail(function (res) {
                _alert('网络错误，任务上报失败，请重试');
            })


    },

    // search

    uploadTaskSearch: function () {

        var data = {
            userId: avalon.vmodels.root.user.id,
            userToken:avalon.vmodels.root.user.token,
            startTime:uploadTask.upload.startTime,
            endTime:uploadTask.upload.endTime,
        }

        $.ajax({
            url: server.queryTask,
            type: 'get',
            dataType: 'json',
            data: data
        })
            .done(function(res) {
                var data = res.values;
                if(res.status == '9200'){
                    $('#uploadTable').bootstrapTable('load', data)
                    $('#uploadTable').bootstrapTable('selectPage', 1);
                }else{
                    $('#uploadTable').bootstrapTable('removeAll');
                    $('#uploadTable').bootstrapTable({});
                }
            })
            .fail(function(res) {
                _alert('网络错误，请刷新尝试！');
                avalon.log(JSON.parse(res) + _.now())
            })
    },

    // choose file
    fileSe: function () {
        var file = $('input[id=lefile]')[0].files[0];
        var formData = new FormData();
        formData.append('file', file);
        $('#fileName').html('<span>' + file.name + '</span>');
        console.log(file);

        $.ajax({
            url: server.fileUpload,
            type: 'POST',
            cache: false,
            data: formData,
            processData: false,
            contentType: false
        }).done(function(res) {
            uploadTask.upload.fileAdrr = res.toString();
            console.log(res);
        }).fail(function(res) {
            $('#fileError').text(res.description);
        });
    },

    clear: function () {
        $('#detailModalBody').html('');
    }

})

// when click row , gain the task id , and gain the task progress
// uploadTask.$watch("upload.taskId",function () {
//     // _alert(avalon.vmodels.uploadTask.upload.taskId)
//
// })

function gainTaskId() {

    $.ajax({
        url: server.jd,
        type: 'get',
        dataType: 'json',
        data: {
            userId: avalon.vmodels.root.user.id,
            userToken:avalon.vmodels.root.user.token,
            taskId:uploadTask.upload.taskId
        }
    })
        .done(function(res) {
            var data = res.values;
            if(res.status == '9200'){
                var data = res.values;
                uploadTask.upload.jdList = avalon.mix(true, [], data);
                $('#upploadTaskModal').modal('show');
            }else{
                _alert(res.description);
            }
        })
        .fail(function(res) {
            _alert('网络错误，请刷新尝试！');
            avalon.log(JSON.parse(res) + _.now())
        })
}



module.exports = uploadTask;